import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate';
import router,{resetRouter} from "@/router";

Vue.use(Vuex)

// 添加新路由
function addNewRoute (menuList)  {
  //console.log(menuList)
  let routes = router.options.routes
  routes.forEach(route=> {
    if (route.path === '/index') { // 找到index路由
      menuList.forEach(menu => { // 遍历菜单列表
        // 构建一个子路由
        let childrenRoute = {
          path: '/' + menu.menuclick,
          name: menu.menuname,
          meta: {
            title: menu.menuname
          },
          component: () => import('@/views/' + menu.menucomponent)
        }
        route.children.push(childrenRoute) // 添加子路由到/index路由下
      })

    }
  })

  //resetRouter() // 重新设置路由
  router.addRoutes(routes) // 最后，调用 router.addRoutes(routes) 方法将更新后的路由列表添加到 Vue 路由中。

}

export default new Vuex.Store({
  state: {
    menu: [], // 菜单列表
    user: {},
  },
  getters: {
    getMenu(state) {
      return state.menu
    },
    getUser(state) {
      return state.user
    }
  },
  mutations: {
    setMenu(state, menuList) {
      state.menu = menuList
      addNewRoute(menuList)
    },
    logout(state) {
      state.user = {}
    },
    setUser(state, user) {
      state.user = user
    }
  },
  plugins: [createPersistedState()],
  actions: {
  },
  modules: {
  }
})
